﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Examine;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 来料检验标准
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class QcReceiveStandardController : ControllerBase
    {
        public QcReceiveStandardController(IQcReceiveStandardServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }

        public IQcReceiveStandardServices Services { get; }
        public LogHelper LogHelper { get; }


        /// <summary>
        /// 获取所有来料检验标准
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-获取所有", ex, HttpContext);
            }


            return Ok(status);
        }



        /// <summary>
        /// 根据来料检验标准编号获取子表
        /// </summary>
        /// <param name="Id">来料检验标准编号</param>
        /// <returns></returns>
        [HttpGet("GetQcReceiveStandardItemById")]
        public async Task<IActionResult> GetQcReceiveStandardItemById([FromQuery] long Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {

                var list = await Services.GetQcProcessStandardItemByNumber(Id);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-获取子表", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 分页获取来料检验标准
        /// </summary>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="Number">检验编号</param>
        /// <param name="Name">检验名称</param>
        /// <param name="Method">检验方式</param>
        /// <returns></returns>

        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string Number, [FromQuery] string Name, [FromQuery] string Method)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                Number = Number ?? "";
                Name = Name ?? "";
                Method = Method ?? "";

                var list = await Services.GetAsync(PageIndex, PageSize, Number, Name, Method);
                status.Data = list;
                status.Count = await Services.GetCountAsync(Number, Name, Method);
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-分页获取", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 新增来料检验标准
        /// </summary>
        /// <param name="model">来料检验标准模型</param>
        /// <param name="QcReceiveStandardItem">来料检验标准明细表 集合，使用字符串序列化数组</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] QcReceiveStandard model, [FromForm] string QcReceiveStandardItem)
        {
            var status = BaseStatus.CreateInstance();
            List<QcReceiveStandardItem> list = new List<QcReceiveStandardItem>();
            try
            {
                if (!string.IsNullOrEmpty(QcReceiveStandardItem))
                {
                    list = JsonConvert.DeserializeObject<List<QcReceiveStandardItem>>(QcReceiveStandardItem);
                    list.ForEach(x => {

                        //重新将编辑的主表信息 赋值给从表
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        x.QcReceiveStandardId = model.Id;

                    });
                }
                model.CreateTime = StringHelper.GetTimeNow();
                model.Creator = User.Identity.Name;
                if (list.Count == 0)
                {
                    status.Code = -1;
                    status.Msg = "新增失败，检查项目必须选择一项以上。";

                    return Ok(status);

                }

                var result = await Services.AddAsync(model, list);
                if (result)
                {
                    status.Msg = "新增成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败,请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-新增", ex, HttpContext);
            }
            return Ok(status);


        }


        /// <summary>
        /// 修改来料检验标准
        /// </summary>
        /// <param name="model">单位模型</param>
        /// <param name="QcProcessStandardItemString">工序检验标准明细表 集合，使用字符串序列化数组</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] QcReceiveStandard model, [FromForm] string QcReceiveStandardItem)
        {
            var status = BaseStatus.CreateInstance();
            List<QcReceiveStandardItem> list = new List<QcReceiveStandardItem>();
            try
            {
                if (!string.IsNullOrEmpty(QcReceiveStandardItem))
                {
                    list = JsonConvert.DeserializeObject<List<QcReceiveStandardItem>>(QcReceiveStandardItem);
                    list.ForEach(x => {

                        //重新将编辑的主表信息 赋值给从表
                        x.UpdateTime = StringHelper.GetTimeNow();
                        x.Updater = User.Identity.Name;
                        x.QcReceiveStandardId = model.Id;

                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = User.Identity.Name;

                if (list.Count == 0)
                {
                    status.Code = -1;
                    status.Msg = "修改失败，检查项目必须选择一项以上。";

                    return Ok(status);

                }
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                {
                    status.Msg = "修改成功";

                    //操作日志
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-修改", ex, HttpContext);
            }

            return Ok(status);
        }




        /// <summary>
        /// 批量删除来料检验标准
        /// </summary>
        /// <param name="Ids">Id数组</param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-批量删除", ex, HttpContext);
            }

            return Ok(status);
        }



        /// <summary>
        /// 删除来料检验标准
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]

        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                {
                    status.Msg = "删除成功";
                }
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                status.Code = -1;
                status.Msg = "服务器异常，请稍后重试！";
                //写日志
                await LogHelper.WriteErrorLog("来料检验标准-删除", ex, HttpContext);
            }

            return Ok(status);
        }
    }
}
